package com.photovoltaic.neo4j.controller;

import com.photovoltaic.neo4j.entity.GraphData;
import com.photovoltaic.neo4j.service.GraphAnalysisService;
import com.photovoltaic.neo4j.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 知识图谱分析控制器
 * 提供产业链分析、企业风险分析、高新技术企业分析等功能
 */
@RestController
@RequestMapping("/api/neo4j/graph-analysis")
@RequiredArgsConstructor
public class GraphAnalysisController {
    
    private final GraphAnalysisService graphAnalysisService;
    private final ProductService productService;
    private static final Logger log = LoggerFactory.getLogger(GraphAnalysisController.class);
    
    @GetMapping("/supply-chain")
    public ResponseEntity<?> getSupplyChainAnalysis(
            @RequestParam String companyName,
            @RequestParam(defaultValue = "2") int depth) {
        try {
            Map<String, Object> result = graphAnalysisService.getSupplyChainAnalysis(companyName, depth);
            GraphData graphData = new GraphData();
            
            // 直接使用服务层处理后的数据
            graphData.setNodes((List<Map<String, Object>>) result.get("nodes"));
            graphData.setLinks((List<Map<String, Object>>) result.get("links"));

            return ResponseEntity.ok(graphData);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                "error", "查询失败",
                "detail", e.getMessage(),
                "timestamp", new Date()
            ));
        }
    }
    
    @GetMapping("/industry")
    public ResponseEntity<Map<String, Object>> getIndustryAnalysis(
            @RequestParam String industryName) {
        return ResponseEntity.ok(graphAnalysisService.getIndustryAnalysis(industryName));
    }
    
    @GetMapping("/company-risks")
    public ResponseEntity<Map<String, Object>> getCompanyRiskAnalysis(
            @RequestParam String industryName,
            @RequestParam(defaultValue = "10") Integer minRiskCount) {
        return ResponseEntity.ok(graphAnalysisService.getCompanyRiskAnalysis(industryName, minRiskCount));
    }
    
    @GetMapping("/high-tech-companies")
    public ResponseEntity<Map<String, Object>> getHighTechCompanyAnalysis(
            @RequestParam String industryName) {
        return ResponseEntity.ok(graphAnalysisService.getHighTechCompanyAnalysis(industryName));
    }

    @GetMapping("/entity/{type}/{name}")
    public ResponseEntity<Map<String, Object>> getEntityByName(
            @PathVariable String type,
            @PathVariable String name) {
        return ResponseEntity.ok(graphAnalysisService.getEntityByName(name, type));
    }

    @GetMapping("/suppliers/direct")
    public ResponseEntity<Map<String, Object>> getDirectSuppliers(
            @RequestParam String companyName) {
        return ResponseEntity.ok(graphAnalysisService.getDirectSuppliers(companyName));
    }

    @GetMapping("/supply-chain-path")
    public ResponseEntity<Map<String, Object>> getSupplyChainPath(
            @RequestParam String sourceCompany,
            @RequestParam String targetCompany,
            @RequestParam(defaultValue = "3") int maxDepth) {
        return ResponseEntity.ok(graphAnalysisService.getSupplyChainPath(
            sourceCompany, targetCompany, maxDepth));
    }

    @GetMapping("/supplier-community")
    public ResponseEntity<List<Map<String, Object>>> getSupplierCommunityAnalysis(
            @RequestParam String companyName) {
        return ResponseEntity.ok(graphAnalysisService.getSupplierCommunityAnalysis(companyName));
    }

    @PostMapping("/companies/features")
    public ResponseEntity<Map<String, Object>> getCompanyByFeatures(
            @RequestBody Map<String, Object> features) {
        return ResponseEntity.ok(graphAnalysisService.getCompanyByFeatures(features));
    }
    
    @GetMapping("/company-stats")
    public ResponseEntity<List<Map<String, Object>>> getCompanyStatsByProvince(
            @RequestParam(required = false) String industryName) {
        return ResponseEntity.ok(graphAnalysisService.getCompanyStatsByIndustry(industryName));
    }

    /**
     * 搜索产品
     * @param keyword 关键词
     * @return 产品列表
     */
    @GetMapping("/search-products")
    public ResponseEntity<?> searchProducts(@RequestParam String keyword) {
        try {
            List<Map<String, Object>> products = productService.searchProducts(keyword);
            return ResponseEntity.ok(products);
        } catch (Exception e) {
            log.error("搜索产品失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "搜索产品失败: " + e.getMessage()));
        }
    }

    /**
     * 获取产品上下游关系
     * @param productName 产品名称
     * @param depth 查询深度
     * @param direction 查询方向 (upstream/downstream/both)
     * @return 产品上下游关系数据
     */
    @GetMapping("/product-chain")
    public ResponseEntity<?> getProductChain(
            @RequestParam String productName,
            @RequestParam(defaultValue = "2") Integer depth,
            @RequestParam(defaultValue = "both") String direction) {
        try {
            Map<String, Object> result = productService.getProductChain(productName, depth, direction);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取产品上下游关系失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "获取产品上下游关系失败: " + e.getMessage()));
        }
    }

    /**
     * 行业企业综合分析
     * 整合行业内企业统计分析、高新技术企业与普通企业对比、企业创新能力评估
     * 
     * @param industryName 行业名称
     * @return 行业企业综合分析数据
     */
    @GetMapping("/industry-comprehensive")
    public ResponseEntity<?> getIndustryComprehensiveAnalysis(
            @RequestParam String industryName) {
        try {
            Map<String, Object> result = graphAnalysisService.getIndustryComprehensiveAnalysis(industryName);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取行业企业综合分析失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "获取行业企业综合分析失败: " + e.getMessage()));
        }
    }

        /**
     * 获取关键材料识别分析结果
     * @return 关键材料分析数据
     */
    @GetMapping("/key-materials")
    public ResponseEntity<?> getKeyMaterialsAnalysis() {
        try {
            Map<String, Object> result = graphAnalysisService.getKeyMaterials();
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取关键材料分析失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "获取关键材料分析失败: " + e.getMessage()));
        }
    }

    /**
     * 获取供应链脆弱性分析结果
     * 评估关键材料的供应稳定性，识别可能导致供应链中断的脆弱点
     * @param materials 要分析的关键材料列表
     * @return 供应链脆弱性分析结果
     */
    @GetMapping("/supply-chain-vulnerability")
    public ResponseEntity<?> getSupplyChainVulnerability(
            @RequestParam(required = false) List<String> materials) {
        try {
            log.info("分析供应链脆弱性: materials={}", materials);
            List<Map<String, Object>> result = graphAnalysisService.getSupplyChainVulnerability(materials);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取供应链脆弱性分析失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "获取供应链脆弱性分析失败: " + e.getMessage()));
        }
    }

    /**
     * 获取替代路径分析结果
     * 分析某一材料缺失或成本上升时的潜在替代方案
     * @param materialName 要分析替代方案的材料名称
     * @param minSimilarity 最小相似度（0-1之间的小数）
     * @return 替代路径分析结果
     */
    @GetMapping("/substitute-analysis")
    public ResponseEntity<?> getSubstituteAnalysis(
            @RequestParam String materialName,
            @RequestParam(required = false, defaultValue = "0.3") Double minSimilarity) {
        try {
            log.info("分析替代路径: materialName={}, minSimilarity={}", materialName, minSimilarity);
            Map<String, Object> result = graphAnalysisService.getSubstituteAnalysis(materialName, minSimilarity);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取替代路径分析失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "获取替代路径分析失败: " + e.getMessage()));
        }
    }
} 